package edu.nyp.locationservicesapp.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import edu.nyp.locationservicesapp.R;
import edu.nyp.locationservicesapp.application.LauncherModel;
import edu.nyp.locationservicesapp.base.BaseActivity;
import edu.nyp.locationservicesapp.constant.IPreferencesIds;

/**
 * 启动页
 */
public class StartActivity extends BaseActivity implements Handler.Callback {
    private Handler mHandler;
    private static final int MSG_CONNECT_DEVICE_SUCCESS = 1; // 连接设备成功
    private static final int REQUEST_CODE = 10;//请求码
    private static long MIN_WAITING_TIME = 3000;  //该页面最短停留0.5s
    private long mCreateTime;
    private LinearLayout mLlWelcome;
    private TextView mTvWelcome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        mHandler = new Handler(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(67108864);
        }
        mCreateTime = System.currentTimeMillis();
        initView();
    }

    private void initView() {
        mLlWelcome = (LinearLayout)findViewById(R.id.ll_welcome);
        mTvWelcome = (TextView)findViewById(R.id.tv_welcome_user);
    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
    }

    private void initData() {
        if (Build.VERSION.SDK_INT >= 23) {   //申请通用权限
            String[] permissions = getPermissions();
            if (permissions != null) {
                requestPermissions(permissions, REQUEST_CODE);
                return;
            }
        }
        boolean isLogin = LauncherModel.getInstance().getSPManager().getBoolean(IPreferencesIds.USER_IS_LOGIN, false);
        if(isLogin){
            mLlWelcome.setVisibility(View.VISIBLE);
            String userName = LauncherModel.getInstance().getSPManager().getString(IPreferencesIds.USER_LOGIN_PHONE, "");
            mTvWelcome.setText(userName);
        }
        final long waitingTime = mCreateTime + MIN_WAITING_TIME - System.currentTimeMillis();
        if(waitingTime > 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(waitingTime);
                        mHandler.sendEmptyMessage(MSG_CONNECT_DEVICE_SUCCESS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            mHandler.sendEmptyMessage(MSG_CONNECT_DEVICE_SUCCESS);
        }
    }

    /**
     * 请求权限列表
     */
    @TargetApi(Build.VERSION_CODES.M)
    private String[] getPermissions() {
        String[] permissions = null;
        List<String> permissionsList = new ArrayList<>();
        addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION);
        addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION);
        if (permissionsList.size() > 0) {
            permissions = new String[permissionsList.size()];
            for (int i = 0; i < permissionsList.size(); i++) {
                permissions[i] = permissionsList.get(i);
            }
        }
        return permissions;
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void addPermission(List<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            int count = grantResults.length;
            for (int i = 0 ;i < count;i++) {
                int grant = grantResults[i];
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
            }
            initData();
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case MSG_CONNECT_DEVICE_SUCCESS:
                boolean isLogin = LauncherModel.getInstance().getSPManager().getBoolean(IPreferencesIds.USER_IS_LOGIN, false);
                Intent intent;
                if(!isLogin) {
                    intent = new Intent(this, LoginActivity.class);
                } else {
                    intent = new Intent(this, EventLocationActivity.class);
                    intent.putExtra("showWelcome", true);
                }
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.activity_in_from_right,R.anim.activity_out_from_left);
                break;
        }
        return true;
    }
}
